package org.su.webadapter.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class PasswordUtil {
	/**
	 * md5加密
	 * 
	 * @param psw
	 * @param seeds
	 * @return
	 */
	public static String encode(String psw, String seeds) {

		String password = psw + seeds;
		return encode(password);
	}

	public static String encode(String password) {
		String result = null;
		if (password != null) {
			try {
				MessageDigest md = MessageDigest.getInstance("MD5");
				md.update(password.getBytes("UTF-8"));

				byte messageDigest[] = md.digest();

				StringBuffer hexString = new StringBuffer();

				for (int i = 0; i < messageDigest.length; i++) {
					String b = Integer.toHexString(0xFF & messageDigest[i]);
					if (b.length() < 2) {
						hexString.append('0');
					}
					hexString.append(b);
				}

				result = hexString.toString();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 得到种子，6位16进制字符
	 * 
	 * @return
	 */
	public static String getSeeds() {
		Random random = new Random();
		String result = Integer
				.toHexString(random.nextInt(0x1000000) + 0x1000000);
		return result.substring(1);
	}
}